import smtplib

from sqlalchemy.ext.serializer import Serializer

from settings import Config

from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import os


def SendEmail():
    """发送邮件"""
    # SMTP的服务器信息
    smtpHost = "smtp.exmail.qq.com"
    sslPort = 465
    senderAdr = "xx@xx.cn"
    senderPwd = "XXXX"
    # 创建SMTP对象
    smtpServer = smtplib.SMTP_SSL(smtpHost, sslPort)
    # # 设置debug模块
    # smtpServer.set_debuglevel(True)
    # 登录
    smtpServer.login(senderAdr, senderPwd)
    # 添加邮件内容
    toReceivers = ["a@xx.cn", "b@xx.cn"]
    ccReceivers = ["d@xx.cn", "e@xx.cn"]
    toAddrs = toReceivers + ccReceivers
    emailSubject = "这是个自动发送的邮件"
    emailContent = EmailContent(senderAdr, emailSubject, toReceivers, ccReceivers)
    emailContent.addBody("html")
    emailContent.addAttachment("英文")
    message = emailContent.msg
    # 发送
    smtpServer.sendmail(senderAdr, toAddrs, message.as_string())
    # 终止SMTP会话
    smtpServer.quit()

SendEmail()


class EmailContent:

    def __init__(self, senderAdr, emailSubject, toReceivers, ccReceivers):
        # 邮件对象
        self.msg = MIMEMultipart()
        # 添加发件人头
        self.msg['From'] = Header("测试" + "<" + senderAdr + ">", 'utf-8')
        # 添加收件人
        if isinstance(toReceivers, str):
            self.msg["To"] = toReceivers
        elif isinstance(toReceivers, list):
            self.msg['To'] = ";".join(toReceivers)
        # 添加抄送人
        if isinstance(ccReceivers, str):
            self.msg["Cc"] = ccReceivers
        elif isinstance(ccReceivers, list):
            self.msg["Cc"] = ";".join(ccReceivers)
            # 添加邮件主题
            self.msg['Subject'] = Header(emailSubject, "utf-8")

    def addBody(self, bodyType):
        """
        添加不同的邮件正文的实例
        1. body为字符串：(如)"这是一个邮件正文内容"
        2. body为html格式的字符串：(如)"<div><p>第一段</p><p>&nbsp;第二段</p></div>"
        3. body正文中包含有图片：
        """
        if bodyType == "string":
            body = "这是一个邮件正文内容"
            mimeText = MIMEText(body, "plain", "utf-8")
            self.msg.attach(mimeText)
        elif bodyType == "html":
            body = "<div><p>第一段</p><p>&nbsp;第二段</p></div>"
            mimeText = MIMEText(body, "html", "utf-8")
            self.msg.attach(mimeText)
        elif "image" in bodyType:
            imageFile = "E://log//test.png"
            imageId = os.path.split(imageFile)[1]
            # 添加内容
            body = '''
                    <p>测试图片为：</p>
                    <p><img src="cid:{imageId}"></p>
                    '''.format(imageId=imageId)
            mimeText = MIMEText(body, "html", "utf-8")
            self.msg.attach(mimeText)
            # 读取图片，并设置图片id用于邮件正文引用
            with open(imageFile, "rb") as fp:
                mimeImage = MIMEImage(fp.read())
            mimeImage.add_header("Content-ID", imageId)
            self.msg.attach(mimeImage)

        def addAttachment(self, attachmentName):
            """
            添加附件
            :return:
            """

        file = "E://log//test.txt"
        # file = "E://log//test.zip"
        # file = "E://log//test.png"
        filePath, fileName = os.path.split(file)
        print("fileName =", fileName)
        enclosure = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
        enclosure['Content-Type'] = 'application/octet-stream'
        if attachmentName == "英文":
            enclosure[
                'Content-Disposition'] = 'attachment; filename="%s"' % fileName
        elif attachmentName == "中文":
            enclosure.add_header("Content-Disposition", "attachment",
                                 filename=("gbk", "", fileName))
        self.msg.attach(enclosure)


def send_register_active_email(to_email, username, token):
    # 主题
    subject = F'感谢您注册{Config.EMAIL_SUBJECT}'
    # 发件人
    sender = Config.EMAIL_FROM
    # 收件人
    receiver = [to_email]
    # 激活地址
    mail_active = Config.EMAIL_ACTIVE
    # html内容
    html_message = f'<h1>%s, 欢迎您成为{Config.EMAIL_SUBJECT}注册会员</h1>' \
                   f'请点击下面链接激活您的账户<br /><a href="%s/user/active/%s/">%s/user/active/%s/</a>' % (
        username, mail_active, token, mail_active, token)
    # 第一个参数为文本内容，第二个参数设置文本格式，第三个 utf-8 设置编码
    message = MIMEText(html_message, 'html', 'utf-8')
    # 发送者
    message['From'] = Header(sender, 'utf-8')
    # 接收者
    message['To'] = Header(to_email, 'utf-8')
    message['subject'] = Header(subject, 'utf-8')
    try:
        # 使用非本地服务器，需要建立ssl连接
        smtpObj = smtplib.SMTP_SSL("smtp.163.com", 465)
        # 邮件登录验证
        smtpObj.login(sender, Config.EMAIL_HOST_PASSWORD)
        smtpObj.sendmail(sender, receiver, message.as_string())
        print("邮件发送成功")
    except smtplib.SMTPException as e:
        print("Error：无法发送邮件.Case:%s" % e)


serializer = Serializer(Config.SECRET_KEY, 3600)
# info = {'confirm': user.id}
info = {'confirm': 1}
token = serializer.dumps(info)  # bytes
token = token.decode()
send_register_active_email('shinxuting@163.com', 'akira', token)
